package com.zdp.rocketmq.producer;

import com.zdp.rocketmq.config.JmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * @author sesshomaru
 * @date 2021/6/21
 */
@Slf4j
@Component
public class ProducerBuilder implements InitializingBean, DisposableBean {

    private DefaultMQProducer producer;

    @Override
    public void afterPropertiesSet() throws Exception {
        producer = new DefaultMQProducer(JmsConfig.GENERAL_PRODUCER_GROUP);
        producer.setNamesrvAddr(JmsConfig.NAME_SERVER);
        producer.setRetryTimesWhenSendFailed(3);
        producer.start();
        log.info("[start] RocketMQ连接====> producerGroup: {}", JmsConfig.GENERAL_PRODUCER_GROUP);
    }

    @Override
    public void destroy() throws Exception {
        if (producer != null) {
            producer.shutdown();
            log.info("[stop]RocketMQ连接<==== producerGroup: {}", JmsConfig.GENERAL_PRODUCER_GROUP);
        }
    }

    public DefaultMQProducer getProducer(){
        return this.producer;
    }
}
